package com.base.lib.utils;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.ImageView;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;


public class UploadHelper {
    public static final int IMAGE_FROM_LOCAL = 111;
    public static final int VIDEO_FROM_LOCAL = 222;
    @NonNull
    private static String TAG = "UploadHelper";
    private static UploadHelper uploadHelper;


    public static synchronized UploadHelper getInstance() {
        if (uploadHelper == null) {
            uploadHelper = new UploadHelper();
        }
        return uploadHelper;
    }

    public static void uploadImage(List<File> files, String url, Callback callback) {
        if (files.size() == 0) {
            return;
        }
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
//        MultipartBody body = builder
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
//                .build();
        for (File file : files) {
            builder.addFormDataPart("avatar_file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file));
        }

        Request request = new Request.Builder().url(url)
                .post(builder.build())
                .addHeader(Constant.APP_TOKEN, SpHelper.getInstance().getToken())
                .build();
        new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build().newCall(request).enqueue(callback);
    }


    /**
     * 压缩bitmap尺寸
     */
    public Bitmap compressImageSizeAndLoadBitmap(String imgpath, ImageView imageView) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap;
        newOpts.inJustDecodeBounds = false;
        int oldWidth = newOpts.outWidth;
        int oldHeight = newOpts.outHeight;
        if (newOpts.outHeight > newOpts.outWidth) {
            oldWidth = newOpts.outHeight;
            oldHeight = newOpts.outWidth;
        }
        int scale = 1;
//		if (oldWidth / imageView.getWidth() > oldHeight / imageView.getHeight()) {
//			scale = oldWidth / imageView.getWidth();
//		} else {
//			scale = oldHeight / imageView.getHeight();
//		}
        if (scale <= 0) {
            scale = 1;
        }
        newOpts.inSampleSize = scale;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        bitmap = BitmapFactory.decodeFile(imgpath, newOpts);
        return bitmap;
    }

    public Bitmap decodeSampledBitmapFromFile(String pathName, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap src = BitmapFactory.decodeFile(pathName, options);
        return createScaleBitmap(src, reqWidth, reqHeight, options.inSampleSize);
    }

    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    private Bitmap createScaleBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight, int inSampleSize) {
// 如果是放大图片，filter决定是否平滑，如果是缩小图片，filter无影响，我们这里是缩小图片，所以直接设置为false
        Bitmap dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false);
        if (src != dst) { // 如果没有缩放，那么不回收
            src.recycle(); // 释放Bitmap的native像素数组
        }
        return dst;
    }

    //从本地相册选择照片上传
    public void selectImageFromStore(@NonNull Activity context, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        context.startActivityForResult(intent, requestCode);
    }

    //从本地相册选择视频上传
    public void selectVideoFromStore(@NonNull Activity context, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换
     */
    @Nullable
    public String getImageAbsolutePath(@Nullable Context context, @Nullable Uri imageUri) {
        if (context == null || imageUri == null) {
            return null;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
                DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri)) {
                return imageUri.getLastPathSegment();
            }
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    public void selectImageFromCamera(@NonNull Activity context, int requestCode, @Nullable File saveImage) {
        if (saveImage == null) {
            Log.i(TAG, "Image file parameter is null.");
            saveImage = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".png");
        }
        int currentapiVersion = Build.VERSION.SDK_INT;
        Log.i(TAG, "---currentapiVersion===" + currentapiVersion);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (currentapiVersion < Build.VERSION_CODES.N) {
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveImage));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        } else {
            if (saveImage.exists()) {
                try {
                    saveImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.DATA, saveImage.getAbsolutePath());
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        context.startActivityForResult(intent, requestCode);
    }

    public void selectVideoFromCamera(@NonNull Activity context, int requestCode, @Nullable File saveVideo) {
        if (saveVideo == null) {
            Log.i(TAG, "Image file parameter is null.");
            saveVideo = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".mp4");
        }
        int currentapiVersion = Build.VERSION.SDK_INT;
        Log.i(TAG, "---currentapiVersion===" + currentapiVersion);
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        if (currentapiVersion < Build.VERSION_CODES.N) {
            intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveVideo));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        } else {
            if (saveVideo.exists()) {
                try {
                    saveVideo.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.DATA, saveVideo.getAbsolutePath());
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        context.startActivityForResult(intent, requestCode);
    }


    /**
     * 获取存储拍照图片的文件
     */
    @Nullable
    public File getCameraSaveFile(@NonNull Context context, long time) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            return new File(context.getExternalCacheDir(), time + ".png");
        } else {
            return new File(context.getCacheDir(), time + ".png");
        }
    }

    @Nullable
    public File getCameraSaveVideoFile(@NonNull Context context, long time) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            return new File(context.getExternalCacheDir(), time + ".mp4");
        } else {
            return new File(context.getCacheDir(), time + ".mp4");
        }
    }

    private String getDataColumn(Context context, @NonNull Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return null;
    }

    public boolean isExternalStorageDocument(@NonNull Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public boolean isDownloadsDocument(@NonNull Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public boolean isMediaDocument(@NonNull Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public boolean isGooglePhotosUri(@NonNull Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}
